package com.android.example.viewexample;

import android.view.View;
import java.lang.Runnable;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Color;

public class MainView extends View implements Runnable{

	private Thread main_thread;
	private boolean is_thread_can_run;
	private Paint paint;
	private int screen_width, screen_height;
	private int frame_count = 0;
	private int FPS = 0;
	private long frame_count_start_time = 0;
	
	public MainView(Context context){
		super(context);
		screen_width = context.getResources().getDisplayMetrics().widthPixels;
		screen_height = context.getResources().getDisplayMetrics().heightPixels;
		paint = new Paint();
	}
	
	@Override
	protected void onDraw(Canvas canvas){
		paint.setColor(Color.WHITE);
		canvas.drawRect(0, 0, screen_width, screen_height, paint);
		paint.setColor(Color.BLACK);
		canvas.drawText("FPS: " + FPS, 5, 50, paint);
		canvas.drawText(""+ System.currentTimeMillis(), 5, 75, paint);		
	}
	
	public void Initialize(){
		main_thread = new Thread(this);
		main_thread.start();
		is_thread_can_run = true;		
	}
	
	public void Destroy(){
		is_thread_can_run = false;
		boolean retry = true;
        do {
            try {
                main_thread.join();
                retry = false;
            } catch (InterruptedException e) {
				e.printStackTrace();
                // we will try it again and again...
            }
        }while(retry);
	}
	
	@Override
	public void run(){
		while(is_thread_can_run){
			if(System.currentTimeMillis() - frame_count_start_time < 1000){
				frame_count ++;
			}else{
				FPS = frame_count;
				frame_count = 0;
				frame_count_start_time = System.currentTimeMillis();
			}
			postInvalidate();
		}
	}
}